package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/4/4 16:20
 */
public class J16 {

    /** https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/ */
    // x的n次方
    public static double myPow(double x, int n) {
        if(x == 1 || n == 0) { return 1; }
        double ans = 1;
        long b = n;
        b = b < 0? -b: b;
        for (int i = 0; i < b; i++) {
            ans *= x;
        }
        System.out.println(ans);
        return n < 0 ? 1 / ans: ans;
    }
    public static double myPow2(double x, int n) {
        double ans = 1;    // 0次方

        long b = n;
        b = b < 0? -b: b;

        for (; b != 0; b >>= 1) {
            if( (b & 1) == 1 ) {
                ans *= x;
            }
            x *= x;
        }
        System.out.println(ans);
        return n < 0 ? 1 / ans: ans;
    }

    // for test
    public static void main(String[] args) {
        double x = 2.00000;
        int n = -19;

        System.out.println(myPow(x, n));
        System.out.println(myPow2(x, n));
        System.out.println(Math.pow(x, n));
    }


}
